<template>
	<div class="tables">
		<el-form :inline="true" :model="formInline" class="demo-form-inline">
			<el-form-item label="频道名称">
				<el-input v-model="formInline.name" placeholder="请输入频道名称" clearable />
			</el-form-item>
			<el-form-item label="频道地址">
				<el-input v-model="formInline.url" placeholder="请输入频道地址" clearable />
			</el-form-item>
			<el-form-item>
				<el-button type="primary" :icon="Search" @click="onSubmit">搜索</el-button>
				<el-button :icon="Refresh" @click="onreset">重置</el-button>
			</el-form-item>
		</el-form>
		<div class="mb-4">
			<el-button :icon="Plus" type="primary" plain @click="addData">新增</el-button>
			<!-- <el-button :icon="EditPen" type="success" @click="editData" plain>修改</el-button> -->
			<el-popconfirm title="确定删除所选内容吗？" @confirm="deleteElement">
				<template #reference>
					<el-button :icon="Delete" type="danger" plain>删除</el-button>
				</template>
			</el-popconfirm>
			<!-- <el-button :icon="Download" type="warning" plain>导出</el-button> -->
		</div>

		<el-table v-loading="loading" ref="multipleTableRef" :data="tableData" style="width: 100%;margin-top: 20px;"
			@selection-change="handleSelectionChange">
			<el-table-column type="selection" :selectable="selectable" width="55" />
			<el-table-column 
				v-for="column in pageData.columns"
				:sortable="column.prop=='channelname'"
				:key="column.prop" 
				:prop="column.prop" 
				:label="column.label" 
				:min-width="column.minWidth"
			>
				<template v-if="column.prop=='enable'" #default="scope">
					<el-switch
					v-model="scope.row.enable" 
					:active-value="1"
					:inactive-value="0"
					@change="enableColumn(scope.row)"
					/>
				</template>
				<template v-if="column.prop == 'url'" #default="scope">
					<span @click="copyurl(scope.row.url)">{{scope.row.url}}</span>
				</template>
				<template v-if="column.prop=='checkurl'" #default="scope">
					<span><el-button @click="checkurlok(scope.row)">检查</el-button></span>
				</template>
			</el-table-column>
			<el-table-column label="操作" class="notranslate">
				<template #default="scope">
					<el-dropdown>
						<el-button>操作</el-button>
						<template #dropdown>
							<el-dropdown-menu>
								<el-dropdown-item @click="editeRowData(scope.row)">
									<icon name="bianji" />修改
								</el-dropdown-item>
								<el-dropdown-item @click="deleteRowData(scope.row)">
									<icon name="shanchu" />删除
								</el-dropdown-item>
								<!-- <el-dropdown-item disabled>
									<icon name="yonghujinyong" />禁用
								</el-dropdown-item> -->
							</el-dropdown-menu>
						</template>
					</el-dropdown>
				</template>
			</el-table-column>
		</el-table>

		<div class="pagination">
			<el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20]"
				:size="size" :disabled="disabled" :background="background"
				layout="total, sizes, prev, pager, next, jumper" :total="totals" locale="zh_CN"
				@size-change="handleSizeChange" @current-change="handleCurrentChange" />
		</div>

		<div class="wxdialog">
			<el-dialog v-model="dialogVisible" :title="Tips?'新增':'修改'" width="600" draggable>
				<div>
					<el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules"
						label-width="auto" class="demo-ruleForm" :size="formSize" status-icon>
						<el-form-item label="所属频道">
							<el-select
								v-model="ruleForm.channelid"
								filterable
								placeholder="请选择所属频道"
							>
								<el-option 
									v-for="item in channel" 
									:key="item.id" 
									:label="item.name"
									:value="item.id"
								>
								</el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="源地址" prop="url">
							<el-input v-model="ruleForm.url" placeholder="请填写源地址" />
						</el-form-item>
						<el-form-item label="是否启用" prop="url">
							<el-switch :active-value="1"
    :inactive-value="0" v-model="ruleForm.isenable" />
						</el-form-item>
					</el-form>
				</div>
				<template #footer>
					<div class="dialog-footer">
						<el-button @click="resetForm(ruleFormRef)">取消</el-button>
						<el-button type="primary" @click="submitForm(ruleFormRef)">
							确定
						</el-button>
					</div>
				</template>
			</el-dialog>
		</div>

	</div>
</template>

<script lang="ts" setup>
	import { ref, reactive, onMounted, getCurrentInstance } from 'vue'
	import type { TableInstance, ComponentSize, FormInstance, FormRules } from 'element-plus'
	import { Search, Refresh, Plus, EditPen, Delete, Download } from '@element-plus/icons-vue'
	const currentPage = ref(1)
	const pageSize = ref(10)
	const totals = ref(0)
	const size = ref<ComponentSize>('default')
	const background = ref(true)
	const disabled = ref(false)
	let dialogVisible = ref(false)
	const loading = ref(true)
	const Tips = ref(true)
	const { proxy } = getCurrentInstance();
	let currentrow = reactive({})
	const pageData = reactive({
		columns: [
			{
				prop: 'classfiyname',
				label: '所属分类',
				minWidth: '100px'
			},
			{
				prop: 'channelname',
				label: '所属频道',
				minWidth: '100px'
			},
			{
				prop: 'url',
				label: '频道地址',
				minWidth: '100px'
			},
			{
				prop: 'enable',
				label: '启用状态',
				minWidth: '100px'
			},
			{
				prop: 'checkurl',
				label: '检测是否可以',
				minWidth: '100px'
			}
		]
	});

	let channel = ref([])

	const getsouce = () => {
		proxy.$http.post('/getsouce',{ "currentPage": currentPage.value, "pageSize": pageSize.value }).then((res) => {
			tableData.value = res.data;
			totals.value=res.totals
		}).catch((error) => {
			console.log(error)
		})
	}

	const getchannel = () => {
		proxy.$http.post('/getchannel',{ "currentPage": 1, "pageSize": 10000 }).then((res) => {
			console.log(res)
			channel.value = res.data;
		}).catch((error) => {
			console.log(error)
		})
	}

	interface User {
		id : number
		classfiyname : string
		classfiyid : number
		name : string

	}

	let tableData : User[] = ref([])
	onMounted(() => {
		getsouce()
		getchannel()
	})

	setTimeout(() => {
		loading.value = false
	}, 2000)
	interface RuleForm {
		name : string,
		channelid:number,
		url:string,
		isenable:boolean
	}

	const formSize = ref<ComponentSize>('default')
	const ruleFormRef = ref<FormInstance>()
	let ruleForm = reactive<RuleForm>({
		channelid: null,
		url: '',
		isenable: true,
		name: ''
	})

	const rules = reactive<FormRules<RuleForm>>({
		name: [
			{ required: true, message: '请填写名称', trigger: 'blur' },
			{ min: 1, max: 30, message: '请输入正确的名称', trigger: 'blur' },
		]
	})

	const submitForm = async (formEl : FormInstance | undefined) => {
		if (!formEl) return
		await formEl.validate((valid, fields) => {
			if (valid) {
				if (Tips.value) { //新增
					const obj = channel.value.find((item) => {
						return item.id == ruleForm.channelid
					})
					
					const newobj = {
						url: ruleForm.url,
						channelname:obj.name,
						channelid: ruleForm.channelid,
						classfiyname:obj.classfiyname,
						classfiyid:obj.classfiyid,
						enable:ruleForm.isenable
					}
					proxy.$http.post('/addsouce', newobj).then((res) => {
						getsouce()
						dialogVisible.value = false
						formEl.resetFields()
					}).catch((error) => {
						console.log(error)
					})
				} else {
					const obj = channel.value.find((item) => {
						return item.id == ruleForm.channelid
					})
					
					const newobj = {
						id:currentrow.id,
						url: ruleForm.url,
						enable:ruleForm.isenable
					}

					proxy.$http.post('/updatesouce', newobj).then((res) => {
						getsouce()
						dialogVisible.value = false
						formEl.resetFields()
					}).catch((error) => {
						console.log(error)
					})
				}

			} else {

				console.log('error submit!', fields)
				return false
			}
		})

	}

	const resetForm = (formEl : FormInstance | undefined) => {
		if (!formEl) return
		formEl.resetFields()
		dialogVisible.value = false
	}

	const options = Array.from({ length: 10000 }).map((_, idx) => ({
		value: `${idx + 1}`,
		label: `${idx + 1}`,
	}))

	const handleSizeChange = (val : number) => {
		console.log(`${val} items per page`)
	}
	const handleCurrentChange = (val : number) => {
		proxy.$http.post('/getsouce',{ "currentPage": val, "pageSize": pageSize.value }).then((res) => {
			tableData.value = res.data
		}).catch((error) => {
			console.log(error)
		})
	}

	const addData = () => {
		Tips.value = true
		dialogVisible.value = true

	}
	
	const copyurl = async(textToCopy)=>{
		await navigator.clipboard.writeText(textToCopy);
	}
	
	const enableColumn = (row)=>{
		
		proxy.$http.post('/updatesouce',row).then((res)=>{
			console.log(res)
		}).catch(()=>{
			
		})
	}

	const editeRowData = (row) => {
		console.log(row.enable)
		Tips.value = false
		dialogVisible.value = true
		ruleForm.url = row.url
		ruleForm.isenable=row.enable
		ruleForm.channelid = row.channelid
		currentrow = row;
	}

	const deleteRowData = (row) => {
		proxy.$http.post('/deletesouce', { "id": row.id }).then((res) => {
			getsouce()
		}).catch((error) => {
			console.log(error)
		})
	}

	const editData = () => {
		Tips.value = false
		dialogVisible.value = true
	}

	const formInline = reactive({
		name: '',
		url:''
	})

	const onSubmit = () => {
		const obj={
			channelname:formInline.name,
			url:formInline.url,
			currentPage:currentPage.value,
			pageSize:pageSize.value
		}
		proxy.$http.post('/searchTablesouce',obj).then((res)=>{
			tableData.value=res.data;
			totals.value=res.totals;
		}).catch((err)=>{
			console.log(err)
		})
	}

	const onreset = () => {
		formInline.name = "";
		formInline.url = "";
	}

	const multipleTableRef = ref<TableInstance>()
	const multipleSelection = ref<User[]>([])

	const selectable = (row : User) => ![].includes(row.id)
	const toggleSelection = (rows ?: User[], ignoreSelectable ?: boolean) => {
		if (rows) {
			rows.forEach((row) => {
				multipleTableRef.value!.toggleRowSelection(
					row,
					undefined,
					ignoreSelectable
				)
			})
		} else {
			multipleTableRef.value!.clearSelection()
		}
	}
	const handleSelectionChange = (val : User[]) => {
		multipleSelection.value = val
	}
	
	const checkurlok = (row) =>{
		proxy.$http.get('/checkurl',{url:row.url}).then((res) => {
			console.log(res)
			if(res.code==200){
				alert("可用")
			}else{
				alert("不可用")
			}
		}).catch((error) => {
			console.log(error)
		})
	}

	const deleteElement = () => {
		console.log(multipleSelection.value)
		const newarr=multipleSelection.value.map((item)=>{
			return item.id
		})
		console.log(newarr)
		proxy.$http.post('/deletesouce', { "id":newarr}).then((res) => {
			getsouce()
		}).catch((error) => {
			console.log(error)
		})
	}
</script>
<style scoped>
	.tables {
		/* width: 98%; */
		margin: 20px auto;
		padding: 20px;
		box-sizing: border-box;
		background: #fff;
	}

	.demo-form-inline .el-input {
		--el-input-width: 220px;
	}

	.demo-form-inline .el-select {
		--el-select-width: 220px;
	}

	/deep/ .el-table th.el-table__cell {
		background-color: #f8f8f8;
	}

	/deep/ .el-dropdown {
		color: #409eff;
		cursor: pointer;
	}

	/deep/ .el-table .cell {
		line-height: unset;
		/* cursor: pointer; */
	}

	/deep/ .el-popup-parent--hidden {
		width: 100% !important;
	}

	.demo-pagination-block+.demo-pagination-block {
		margin-top: 10px;
	}

	.demo-pagination-block .demonstration {
		margin-bottom: 16px;
	}

	.pagination {
		margin: 20px auto;
		display: flex;
		justify-content: flex-end;
	}
</style>